<template>
  <ElDrawer v-model="visible" direction="ttb" size="80%" :with-header="false" :lock-scroll="false">
    <ElForm ref="form" label-width="auto" :model="purchaseBill">
      <ElRow>
        <ElCol :span="8">
          <ElFormItem label="供货商" prop="supplier">
            <ElInput v-model="purchaseBill.supplier"></ElInput>
          </ElFormItem>
        </ElCol>
      </ElRow>
      <ElRow>
        <ElCol :span="8">
          <ElFormItem label="订货日期" prop="orderDate">
            <ElDatePicker v-model="purchaseBill.orderDate" style="width: 100%"></ElDatePicker>
          </ElFormItem>
        </ElCol>
        <ElCol :span="8" :offset="8">
          <ElFormItem label="交货日期" prop="receiveDate">
            <ElDatePicker v-model="purchaseBill.receiveDate" style="width: 100%"></ElDatePicker>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <ElDivider>detail</ElDivider>
      <ElButton size="small" icon="Delete" type="danger" @click="removeItems()"></ElButton>
      <ElButton size="small" icon="Plus" type="success" @click="open4AddItems()"></ElButton>

      <ElTable
        ref="table"
        :data="purchaseBill.items"
        @selection-change="(rows: any) => (selected = rows)"
        show-summary
        :summary-method="summaryMethod"
      >
        <ElTableColumn type="selection" width="64" />
        <ElTableColumn prop="goodsCode" label="物品编号"></ElTableColumn>
        <ElTableColumn prop="goodsName" label="品名"></ElTableColumn>
        <ElTableColumn label="单价">
          <template #default="{ row }">
            <ElInputNumber size="small" v-model="row.price"></ElInputNumber>
          </template>
        </ElTableColumn>
        <ElTableColumn label="数量">
          <template #default="{ row }">
            <ElInputNumber size="small" v-model="row.quantity"></ElInputNumber>
          </template>
        </ElTableColumn>
        <ElTableColumn label="金额">
          <template #default="{ row }">
            <div>{{ (row.quantity * row.price).toFixed(2) }}</div>
          </template>
        </ElTableColumn>
      </ElTable>

      <ElDivider>operator</ElDivider>
      <ElDescriptions>
        <ElDescriptionsItem label="审核人"></ElDescriptionsItem>
        <!-- <ElDescriptionsItem label="经办人">{{ account.nickname }}</ElDescriptionsItem> -->
        <ElDescriptionsItem label="经办人">{{
          translateSimple(userInfo.userId)
        }}</ElDescriptionsItem>
      </ElDescriptions>
      <ElButton type="primary" @click="insert()">保存购物单</ElButton>
    </ElForm>
    <MaterialSupport ref="support" @post-add-items="postAddItems"></MaterialSupport>
  </ElDrawer>
</template>
<script lang="ts">
import { Material } from '@/entity/material.entity'
import { PurchaseItem, PurchaseBill } from '@/entity/purchase.entity'
// import { accountStore } from '@/stores/account'
import { useMenuStore } from '@/stores/menu'
/**
 * 页面核心数据结构体说明文档
 *
 *
 */
// import from
// class Person {
//   name: string
//   age: number = 11
// }
// interface Person2 {
//   name: string
//   age: number
// }
// type Person3 = {
//   name: string
//   age: number
// }

export default defineComponent({
  name: 'PurchaseInsert',
  emits: ['postInsert'],
  props: {
    sampleP: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      sampleD: 'value',
      visible: false,
      purchaseBill: {
        supplier: 'tesla实验室-SC009',
        orderDate: null,
        receiveDate: null,
        items: [
          {
            goodsCode: 'MT16828553890490023',
            goodsName: '开关',
            price: 12.05,
            quantity: 2,

            itemId: 0,
            billFk: '',
            priority: 0
          }
        ] as Array<PurchaseItem>,

        billId: '',
        billState: 'toSubmit',
        amount: 0,
        nextItemId: 0,
        applier: '',
        applyTime: null,
        auditor: '',
        auditTime: null,
        auditMsg: '',
        history: '',
        updateTime: null
      } as PurchaseBill,
      selected: [] as Array<PurchaseItem>
    }
  },
  computed: {
    ...mapState(useMenuStore, ['userInfo'])
    /* sampleC() {
      return this.sampleD + "--";
    }, */
  },
  created() {},
  mounted() {
    // this.purchaseBill.items = []
  },
  methods: {
    ...mapActions(useMenuStore, ['translateSimple']),
    // sampleM() {},
    show() {
      this.visible = true
    },
    open4AddItems() {
      const support: any = this.$refs.support
      support.show()
    },
    postAddItems(selectedItems: Array<Material>) {
      console.log('采购单页面接收到的是数据', selectedItems)
      // 数据格式化
      const itemsToAdd: Array<PurchaseItem> = selectedItems.map((e) => {
        let p = new PurchaseItem()
        p.goodsCode = e.materialCode
        p.goodsName = e.materialLable
        p.price = e.suggestPrice
        p.quantity = 1
        return p
      })
      console.log('格式化的数据', itemsToAdd)
      // this.purchaseBill.items
      const finalItems = lodash.unionBy(this.purchaseBill.items, itemsToAdd, 'goodsCode')
      this.purchaseBill.items = finalItems
    },
    removeItems() {
      // this.selected;
      //
      const r = lodash.differenceBy(this.purchaseBill.items, this.selected, 'goodsName')
      // console.log(r)
      this.purchaseBill.items = r
    },
    summaryMethod() {
      const line = []
      line[0] = '总计'
      let amount = 0
      this.purchaseBill.items.forEach((item) => {
        amount += item.price * item.quantity
      })
      line[5] = amount.toFixed(2)
      return line
    },
    async insert() {
      const res = await axios({
        method: 'post',
        url: '/purchase/insert',
        data: this.purchaseBill
      })
      ElMessage.success('保存成功')
      this.$emit('postInsert', 1)
      this.visible = false
      // console.log(res.data)
    }
  },
  watch: {
    // sampleP(n, o) {},
  }
})
</script>

<!--<style scoped>-->
<style lang="scss" scoped>
.el-form {
  width: 1000px;
  margin-left: 160px;
}
</style>
